// web/src/app/api/(learn)/course/[courseId]/chapters/reorder/route.ts

import {NextRequest, NextResponse} from "next/server";
import {currentUser} from "@/lib/auth";
import {db} from "@/lib/db";

export async function PUT(
    req: NextRequest,
    {params}: { params: { courseId: string } }
) {
    try {
        const user = await currentUser()
        if (!user) return new NextResponse('Unauthorized', {status: 401})

        const {list} = await req.json()

        const courseOwner = await db.course.findUnique({
            where: {
                id: params.courseId,
                userId: user.id
            }
        })

        if (!courseOwner) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        for (let item of list) {
            await db.chapter.update({
                where: {id: item.id},
                data: {position: item.position}
            })
        }

        return NextResponse.json('Success', {status: 200})
    } catch (e) {
        console.error('[REORDER]', e)
        return new NextResponse('Internal Server Error', {status: 500})
    }
}